package com.gl.basis.auth.shiro.handler;

import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gl.basis.auth.constants.AuthorityConstants;
import com.gl.basis.auth.response.ProfileResult;
import com.gl.basis.auth.util.JWTUtil;

import io.jsonwebtoken.Claims;

/**
 * 当token数据发生变化时，刷新当前token数据
 * 
 * @author Administrator
 *
 */
@Component
public class RefurbishTokenHandler extends HandlerInterceptorAdapter {

	private static final Logger logger = LoggerFactory.getLogger(RefurbishTokenHandler.class);

	/**
	 * 简化获取token数据的代码编写（判断是否登录） 1.通过request获取请求token信息 2.从token中解析获取claims
	 * 3.将claims绑定到request域中
	 */
	@Resource
	private JWTUtil jwtUtil;

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		logger.info("后置拦截器。。。。。。。。");
		String Authorization = request.getHeader(AuthorityConstants.AUTHORIZATION_HEADER);
		if (StringUtils.isNotBlank(Authorization)) {
			String token = Authorization.replace(AuthorityConstants.BEARER_HEADER, "");
			Claims parseJwt = jwtUtil.parseJwt(token);
			//获取token 中的数据
			Object obj = parseJwt.get("data");
			ProfileResult result = null;
			if (obj instanceof Map) {
				result = JSONObject.parseObject(JSON.toJSONString(obj), ProfileResult.class);
			}
			if (null != result && null != result.getExpDate() && differentDaysByMillisecond(result.getExpDate())) {
				String jwt = jwtUtil.createJwt(result.getUserId(), result.getMobile(), result);
				response.setHeader(AuthorityConstants.AUTHORIZATION_HEADER, AuthorityConstants.BEARER_HEADER + jwt);
				logger.info("刷新token:>>>>>>>> {} ; {}",result.getUserId(),result.getUsername());
			}
			
		}

	}

	/**
	 * 计算时间是否小于半小时
	 * 
	 * @param exdate
	 * @return
	 */
	private static boolean differentDaysByMillisecond(Date exdate) {
		return (new Date().getTime() - exdate.getTime()) < 1800000L;
	}

}
